<template>
  <div class="article-form form-contain">
    <div class="article-state">
      <!-- 切换列表 -->
      <el-radio-group v-model="radio1" @change="_isPutaway">
        <el-radio-button label="1">出售中</el-radio-button>
        <el-radio-button label="0">仓库中</el-radio-button>
      </el-radio-group>      
    </div>
    <div class='article-content'>
      <!-- 跳转详情 -->
      <div class='article-head'>
        <el-button type="primary" size='small' @click="changeRoute('articleClassify')">课程分类</el-button>
        <el-button type="primary" size='small' @click="_releaseShop()">发布课程</el-button>
      </div>
      <!-- 筛选 -->
      <div class='article-select'>
        <span class='shop'>课程名称 :</span>
        <el-input
          v-model="input1"
          clearable
          style="width:15%">
        </el-input>
        <span class='shop'>课程分类 :</span>
        <el-select v-model="value" placeholder="请选择" clearable>
          <el-option
            v-for="item in options1"
            :key="item.id"
            :label="item.cat_name"
            :value="item.id">
          </el-option>
        </el-select>
        <span class='shop'>课程分组 :</span>
        <el-select v-model="value2" placeholder="请选择" clearable>
          <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.label">
          </el-option>
        </el-select>
        <span class="select-box">
          <el-button size="mini" @click="_condition">筛选</el-button>        
          <span @click="_claerCondition">清空筛选条件</span>
        </span>
      </div>
      <!-- 列表 -->
      <div class="article-table">
        <el-table
          fixed
          ref="multipleTable"
          :data="tableData3"
          tooltip-effect="dark"
          style="width: 100%"
          header-row-class-name='sss'
          @selection-change="handleSelectionChange"
          v-loading.body="listLoading"
          element-loading-text="拼命加载中">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column           
            label="课程名称"
            width="400"
            show-overflow-tooltip>
            <template slot-scope="scope1">
              <img :src="scope1.row.image_url" alt="" srcset="" class="table-img">
              <span class="table-msg">课程名称 : {{scope1.row.goods_name}}</span>
              <span class="table-msg">课程编号 : {{scope1.row.goods_id}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="cat_name"
            label="课程分类"
            width="120">
          </el-table-column>
          <el-table-column
            prop="goods_price"
            label="价格"
            width="120">
          </el-table-column>
          <el-table-column
            prop="start_date"
            label="创建时间"
            width="220"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="goods_stock"
            label="班容量">
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="_editShop(scope.row.id)">编辑</el-button>
            </template>
          </el-table-column>             
        </el-table>
        <div style="margin-top: 20px">
          <el-button @click="_modify">改分组</el-button>
          <el-button @click="_shelves()">{{radio1 === '0'?'上架':'下架'}}</el-button>
          <el-button @click="_deletes()">删除</el-button>
        </div>
      </div>
      <!-- 分页 -->
      <div class='pagination-box'>
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page="currentPage4"
          :page-size="10"
          layout="prev, pager, next, total, jumper"
          :total="totalPage">
        </el-pagination>
      </div>
    </div>
    <!-- 发布课程 -->
    <el-dialog title='发布课程' :visible.sync="dialogFormVisible">
      <div style="margin-bottom:20px">
        <span><span class='dialog-x'>*</span>课程名:</span>
        <el-input
        v-model="form.input"
        placeholder="例如：小学初阶兴趣素质培养课"
        style="width:240px;margin-left:20px"></el-input>
      </div>
      <div class='dialog-time'>
        <span><span class="dialog-x">*</span>课程学期:</span>
        <el-date-picker
          v-model="form.value1"
          type="date"
          placeholder="开始时间"
          format="yyyy 年 MM 月 dd 日"
          value-format="timestamp">
        </el-date-picker>
        <span>至</span>
        <el-date-picker
          v-model="form.value2"
          type="date"
          placeholder="结束时间"
          format="yyyy 年 MM 月 dd 日"
          value-format="timestamp"
          @blur="_showTime">
        </el-date-picker>
      </div>
      <div class='dialog-time' v-if="showTime1 === 1">
        <span style="margin-bottom:20px;display:block"><span class="dialog-x">*</span>上课时间:</span>
        <el-checkbox-group v-model="checkList">
          <el-checkbox v-for="(item, index) in checkList1" :key="index" :label="item"></el-checkbox>
        </el-checkbox-group>
      </div>
      <div class='dialog-time' v-if="showTime1 === 2">
        <span style="margin-bottom:20px;display:block"><span class="dialog-x">*</span>上课时间:</span>
        <el-checkbox-group v-model="checkList" @change="_changeTime1">
          <el-checkbox label="星期日"></el-checkbox>
          <el-checkbox label="星期一"></el-checkbox>
          <el-checkbox label="星期二"></el-checkbox>
          <el-checkbox label="星期三"></el-checkbox>
          <el-checkbox label="星期四"></el-checkbox>
          <el-checkbox label="星期五"></el-checkbox>
          <el-checkbox label="星期六"></el-checkbox>
        </el-checkbox-group>
      </div>
      <div v-for="(item, index) in weeks" style="padding:20px 0px;" :key="index" v-if='checkList.includes(item.name)'>
        <span>{{item.name}}</span>
        <el-time-picker
          style="margin-bottom:20px;width:40%;margin-left:20px"
          value-format="timestamp"
          is-range
          v-if='item.times.length > 0 && weeks[index].times[m]'
          v-for="(i, m) in item.times"
          :key="m"
          v-model="weeks[index].times[m]"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围">
        </el-time-picker>
        <el-button type="primary" @click="_addTime(index)" style="margin-left:20px">+添加时间</el-button>
      </div>
      <div class='dialog-theme'>
        <span><span class='dialog-x'>*</span>课程主图:</span>
        <el-upload
          class="avatar-uploader"
          ref="upload"
          action="https://jyapi.epanshi.com/api/uploadFile/"
          :file-list="fileList"
          :on-change="changeImg"
          :before-remove="_removeImg"
          :http-request="_loadImg"
          :on-exceed='exced'
          list-type="picture-card"
          :before-upload="beforeAvatarUpload"
          :limit="1">
          <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        <p>此处为课程主图：</p>
        <p>建议使用宽800像素*高800像素的图片;点击下方"确认提交"按钮后生效.最多上传1张</p>
      </div>
      <div class='dialog-class'>
        <span><span class="dialog-x">*</span>课程分类:</span>
        <el-select v-model="form.value5" filterable placeholder="请选择" style="width:30%">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.cat_name"
            :value="item.cat_name">
          </el-option>
        </el-select>
        <el-button type="primary" size='mini' @click="changeRoute('articleClassify')">新建分类</el-button>
      </div>
      <div class='dialog-class'>
        <span><span class="dialog-x">*</span>课程分组:</span>
        <el-select v-model="form.value7" filterable placeholder="请选择" style="width:30%">
          <el-option
            v-for="item in options3"
            :key="item.value"
            :label="item.label"
            :value="item.label">
          </el-option>
        </el-select>
      </div>
      <div class='dialog-class'>
        <span><span class="dialog-x">*</span>上课地址:</span>
        <el-select v-model="form.value6" filterable placeholder="请选择" style="width:30%">
          <el-option
            v-for="item in option4"
            :key="item.id"
            :label="item.address"
            :value="item.address">
          </el-option>
        </el-select>
      </div>
      <div style="margin-bottom:20px">
         <span><span class='dialog-x'>*</span>价&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;格:</span>
         <el-input
         type="number"
         v-model="form.input1"
         placeholder="单位(元)"
         prefix-icon="el-icon-date"
         style="width:240px;margin-left:20px"></el-input>
         <span style="color:#929292">该价格为售卖价格</span>
      </div>
      <div style="margin-bottom:20px">
         <span><span class='dialog-x'>*</span>班 容 量:</span>
         <el-input
         type="number"
         v-model="form.input2"
         placeholder="0"
         style="width:240px;margin-left:20px"></el-input>
         <span style="color:#929292">班容量为0是课程不可售卖</span>
      </div>
      <div style="margin-bottom:20px">
        <span>课程编码:</span>
        <el-input
        v-model="form.input3"
        style="width:240px;margin-left:20px"></el-input>
      </div>
      <div style="margin-bottom:20px">
         <span><span class='dialog-x'>*</span>客服电话:</span>
         <el-input
         type="number"
         v-model="form.input4"
         placeholder="请输入电话号码"
         style="width:240px;margin-left:20px"></el-input>
         <span style="color:#929292">提供客服电话以便买家咨询</span>
      </div>
      <div style="margin-bottom:20px">
        <span><span class='dialog-x'>*</span>上架时间:</span>
        <el-radio v-model="form.radio" label="1" style="margin-left:20px">立即上架售卖</el-radio>
        <el-radio v-model="form.radio" label="0">暂不售卖,放入仓库</el-radio> 
      </div>
      <vue-editor :form='form' keyname='contentText' ref="editor" :width='100'></vue-editor>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size='small'>取 消</el-button>
        <el-button @click="_addClass" size="small" type='primary'>确 定</el-button>
      </div>
    </el-dialog>
    <!-- 改分组 -->
    <el-dialog title='修改分组' :visible.sync="dialogFormVisible1">
      <span class='shop'>课程分组 :</span>
      <el-select v-model="value3" placeholder="请选择" style="width:30%;margin-left:30px;margin-bottom:20px;">
        <el-option
          v-for="item in options2"
          :key="item.value"
          :label="item.label"
          :value="item.label">
        </el-option>
      </el-select>
      <el-button type="primary" style="display:block;margin-left:80%" @click="_modifiedGrouping">确定</el-button>
    </el-dialog>
  </div>
</template>

<script>
import {addCourseList, courseClassification, deleteClassification, changeClassification, shelves, addClassification, selectCourseList} from '@/api/course'
import {loadImg} from '@/api/img'
import {getAddress} from '@/api/address'
import VueEditor from '@/components/Editor'
export default {
  components: {
    VueEditor
  },
  data () {
    return {
      radio1: 1,
      input1: '',
      options: [], // 添加课程分类
      options1: [], // 课程分类
      value: '',
      options2: [{  // 课程分组
        value: '选项1',
        label: '全部课程'
      }, {
        value: '选项2',
        label: '最新课程'
      }, {
        value: '选项3',
        label: '热门课程'
      }, {
        value: '选项4',
        label: '免费课程'
      }],
      options3: [{  // 添加课程分组
        value: '选项1',
        label: '全部课程'
      }, {
        value: '选项2',
        label: '最新课程'
      }, {
        value: '选项3',
        label: '热门课程'
      }, {
        value: '选项4',
        label: '免费课程'
      }],
      value2: '',
      value3: '',
      tableData3: [],
      multipleSelection: [],
      currentPage4: 1,
      totalPage: null,
      listLoading: true,
      dialogFormVisible: false,
      dialogFormVisible1: false,
      form: {
        input: '',
        input1: '',
        input2: '',
        imageUrl: '',
        value1: '',
        value2: '',
        value5: '',
        value6: '',
        input3: '',
        input4: '',
        value7: '',
        radio: '0',
        id: null,
        contentText: ''
      },
      option4: [], // 地址
      showTime1: 0, // 课程时间格式
      checkList: [], // 总日期
      checkList1: [], // <7天日期
      weeks: [],
      fileList: [],
      imgList: ''
    }
  },
  methods: {
    // 清空筛选
    _claerCondition () {
      this.value = ''
      this.input1 = ''
      this.value2 = ''
    },
    _condition () {
      this.load()
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    _modify () {
      if (this.multipleSelection.length === 0) {
        this.$message.warning('请选择课程')
      } else {
        this.dialogFormVisible1 = true
      }
    },
    // 编辑
    _editShop (id) {
      selectCourseList({id: id}).then(res => {
        if (res.code === 1) {
          let obj1 = res.data.dataList[0]
          let startDate = new Date(obj1.start_date).getTime()
          let endDate = new Date(obj1.end_date).getTime()
          let isPutaway = obj1.is_putaway.toString()
          let weeks = JSON.parse(obj1.weeks)
          this.weeks = weeks
          this.form.input = obj1.goods_name
          this.form.value5 = obj1.cat_name
          this.form.input1 = obj1.goods_price
          this.form.input2 = obj1.goods_stock
          this.form.value6 = obj1.address
          this.form.input4 = obj1.service_tel
          this.form.input3 = obj1.goods_code
          this.form.radio = isPutaway
          this.form.value7 = obj1.group_name
          this.form.imageUrl = obj1.image_url
          this.form.value1 = startDate
          this.form.value2 = endDate
          this.form.contentText = obj1.goods_desc
          this.form.id = id
          this.imgList = obj1.image_url
          let arr1 = []
          for (const item of this.weeks.entries()) {
            if (item[1].times.length !== 0) {
              arr1.push(item[1].name)
            }
          }
          this.checkList = arr1
          if (this.weeks[0].name === '星期日') {
            this.showTime1 = 2
          } else {
            this.checkList1 = arr1
            this.showTime1 = 1
          }
          setTimeout(() => {
            this.$refs.editor.getContentText()
          }, 50)
          this.dialogFormVisible = true
        }
      }).catch(err => {
        console.log(err)
      })
    },
    // 改分组
    _modifiedGrouping () {
      if (this.value3 === '') {
        this.$message.warning('请选择分组')
      } else {
        let arr = []
        for (var i = 0; i < this.multipleSelection.length; i++) {
          arr.push(this.multipleSelection[i].goods_id)
        }
        let params = {
          group_name: this.value3,
          goods_id: arr
        }
        changeClassification(params).then(res => {
          if (res.code === 1) {
            this.dialogFormVisible1 = false
            this.$message.success('修改成功')
            this.load()
          }
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 下架课程
    _shelves () {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择课程',
          type: 'warning'
        })
      } else {
        let arr = []
        for (var i = 0; i < this.multipleSelection.length; i++) {
          arr.push(this.multipleSelection[i].goods_id)
        }
        let params = {
          is_putaway: this.radio1,
          goods_id: arr
        }
        shelves(params).then(res => {
          if (res.code === 1) {
            this.load()
            this.$message({
              message: '操作成功',
              type: 'success'
            })
          } else {
            this.$message({
              message: '操作失败',
              type: 'warning'
            })
          }
        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 删除订单
    _deletes () {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择课程',
          type: 'warning'
        })
      } else {
        this.$confirm('此操作将删除课程, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let arr = []
          for (var i = 0; i < this.multipleSelection.length; i++) {
            arr.push(this.multipleSelection[i].goods_id)
          }
          let params = {
            goods_id: arr
          }
          deleteClassification(params).then(res => {
            if (res.code === 1) {
              this.load()
              this.$message({
                message: '删除成功',
                type: 'success'
              })
            }
          }).catch(err => {
            console.log(err)
          })
        })
      }
    },
    _isPutaway (val) {
      this.load()
    },
    // 添加课程
    _addClass () {
      let arr1 = []
      for (const item of this.weeks) {
        for (let i = 0; i < item.times.length; i++) {
          if (item.times[i] === null) {
            item.times.splice(i, 1)
          }
        }
        arr1.push({name: item.name, times: item.times})
      }
      let params = {
        goods_name: this.form.input, // 课程名称
        cat: this.form.value5,  // 课程分类
        goods_price: this.form.input1,  // 课程价格
        goods_stock: Number(this.form.input2), // 库存量
        address: this.form.value6, // 地址
        service_tel: this.form.input4, // 客服电话
        goods_code: this.form.input3, // 课程编码
        is_putaway: Number(this.form.radio), // 是否立即上架
        start_date: this.form.value1 / 1000, // 开始时间
        end_date: this.form.value2 / 1000, // 结束时间
        weeks: arr1, // 时间数组
        group_name: this.form.value7, // 分组
        image_url: this.imgList, // 图片
        goods_desc: this.form.contentText, // 富文本
        id: this.form.id // 课程id
      }
      addClassification(params).then(res => {
        if (res.code === 1 || 2) {
          this.dialogFormVisible = false
          this.load()
          this.$message({
            type: 'success',
            message: res.msg
          })
        } else {
          this.$message({
            type: 'warning',
            message: res.msg
          })
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleCurrentChange (val) {
      this.currentPage4 = val
      this.load()
    },
    changeRoute (name) {
      this.$router.push({name: name})
    },
    // 上传图片
    _uploadImg (fileList) {
      this.imgList = []
      fileList.forEach(item => {
        if (item.raw) {
          let formData = new FormData()
          formData.append('file', item.raw)
          loadImg(formData).then(res => {
            if (res.code === 1) {
              this.imgList = res.data
            }
          })
        }
      })
    },
    exced () {
      this.$message({
        type: 'warning',
        message: '轮播图最多只能上传1张图片！'
      })
    },
    changeImg (file, fileList) {
      this._uploadImg(fileList)
    },
    _removeImg (file, fileList) {
      let list = []
      this.fileList.forEach(item => {
        list.push(item.url)
      })
      if (list.indexOf(file.url) === -1) {
        this._uploadImg(fileList)
      } else {
        this.fileList.splice(list.indexOf(file.url), 1)
      }
    },
    _loadImg (file) {
    },
    // 限制图片
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      console.log(!isJPG && !isPNG)
      if (!isJPG && !isPNG) {
        this.$message.error('上传图片必须是JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    _releaseShop () {
      this.form.input = ''
      this.form.value5 = ''
      this.form.input1 = ''
      this.form.input2 = ''
      this.form.value6 = ''
      this.form.input4 = ''
      this.form.input3 = ''
      this.form.radio = '0'
      this.form.value7 = ''
      this.form.value1 = ''
      this.form.value2 = ''
      this.form.imageUrl = ''
      this.form.contentText = ''
      this.form.id = null
      this.weeks = []
      this.checkList1 = []
      this.checkList = []
      this.showTime1 = 0
      this.fileList = []
      this.imgList = ''
      setTimeout(() => {
        this.$refs.editor.clearContentText()
      }, 50)
      this.dialogFormVisible = true
    },
    // 选择时间格式
    _showTime () {
      let dayTime = (this.form.value2 - this.form.value1) / 86400000
      if (this.form.value1 !== '') {
        if (dayTime >= 0 && dayTime <= 6) {
          this.showTime1 = 1
          this.checkList1 = []
          this.weeks = []
          for (let i = 0; i <= dayTime; i++) {
            let time = new Date(this.form.value1 + 86400000 * i)
            let myDate = time.getMonth() + 1 + '月' + time.getDate() + '号'
            this.checkList1.push(myDate)
            this.weeks.push({name: myDate, times: []})
          }
        } else if (dayTime >= 0 && dayTime > 6) {
          this.showTime1 = 2
          let arr1 = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']
          this.weeks = []
          for (let i = 0; i < arr1.length; i++) {
            this.weeks.push({name: arr1[i], times: []})
          }
        } else {
          this.showTime1 = 0
        }
      }
    },
    // 添加时间
    _addTime (index) {
      this.weeks[index].times.forEach((item, i) => {
        if (item === null) {
          this.weeks[index].times.splice(i, 1)
        }
      })
      if (this.weeks[index].times.length <= 2) {
        this.weeks[index].times.push([-7200000, 7200000])
      }
    },
    // 删除时间
    _changeTime1 (value) {
      this.weeks.forEach(item => {
        if (!value.includes(item.name)) {
          item.times = []
        }
      })
    },
    load () {
      let params = {
        group_name: this.value2,
        cat_name: this.value,
        goods_name: this.input1,
        page: this.currentPage4,
        is_putaway: this.radio1
      }
      addCourseList(params).then(res => {
        console.log(res.data)
        for (let i = 0; i < res.data.dataList.length; i++) {
          res.data.dataList[i].goods_price = res.data.dataList[i].goods_price + '元'
        }
        this.totalPage = Math.ceil(res.data.total)
        this.tableData3 = res.data.dataList
        this.listLoading = false
      }).catch(err => {
        console.log(err)
      })
    }
  },
  mounted () {
    // 课程列表初始化
    this.load()
    // 课程分类初始化
    courseClassification().then(res => {
      this.options = res.data
      this.options1 = res.data
    }).catch(err => {
      console.log(err)
    })
    // 课程地址
    getAddress().then(res => {
      if (res.code === 1) {
        this.option4 = res.data
      }
    }).catch(err => {
      console.log(err)
    })
  }
}
</script>

<style lang='less'>
  .v-modal{
    z-index: 509 !important;
  }
  .article-form{
    font-size: 14px;
    width: 100%;
    box-sizing: border-box;
    input::-webkit-outer-spin-button,
    input::-webkit-inner-spin-button {
      -webkit-appearance: none;
    }
    input[type="number"]{
      -moz-appearance: textfield;
    }
    .el-dialog__wrapper{
      z-index: 510 !important;;
    }
    .el-select{
      width: 15%;
    }
    .article-state{
      margin-left: 40px
    }
    .article-content{
      background: #ffffff;
      padding-top:20px; 
      .article-head{
        margin-bottom: 40px;
      }
      .article-select{
        width: 95%;
        background: #304156;
        color: #ffffff;
        margin-bottom: 30px;
        padding: 30px 0;
        .el-input{
          margin-left: 1% 
        }
        .shop{
          margin-left: 1%;
        }
        .select-box{
          width:50%;
          margin-left: 60px;
          margin-top: 30px;
          >span{
            display: inline-block;
            margin-left: 10px;
            // color: #3f76b5;
            cursor: pointer;
          }
        }
      }
      .article-table{
        width: 95%;
        min-height: 500px;
        .table-img{
          height: 71px;
          width: 60px;
          float: left;
        }
        .table-msg{
          display: block;
          line-height: 30px;
          margin-left: 80px;
        }
      }
      .pagination-box{
        width: 90%;
        display: flex;
        justify-content: flex-end;
      }
    }
    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      line-height: 148px;
      text-align: center;
    }
    .avatar {
      width: 148px;
      height: 148px;
      display: block;
    }
    .dialog-theme{
      margin-top:20px;
      p{
        color:rgb(170, 170, 170);
        font-size:14px
      }
    }
    .dialog-class{
      margin-bottom:20px;
      .el-select{
        margin-left: 20px;
      }
    }
    .dialog-time{
       margin-bottom:20px;
       .el-date-editor {
         width: 30%;
         margin-left:10px;
         margin-right: 10px;
       }
       .el-checkbox{
         height: 50px;
       }
    }
    .dialog-x{
      color:rgb(229, 28, 35)
    }
  }
</style>
